import axios from 'axios';
import React, { Component } from 'react'
import './index.css';
export default class Goods extends Component {

    state = {
        goods: [],
        page: 1
    }

    render() {
        return (
            <div className="good-container">
                <h2>商品列表</h2>
                <div className="goods-list">
                    {this.state.goods.map(item => {
                        return <div className="item" key={item.id}>
                            <div className="img"><img src={'http://192.168.43.31:8090' + item.img} alt="" /></div>
                            <div className="price">
                                ￥{item.price}
                            </div>
                            <div className="gap-5"></div>
                            <div className="title">
                                {item.title}
                            </div>
                            <div className="gap-5"></div>
                            <div className="shop">
                                {item.shop}
                            </div>
                            <div className="gap-5"></div>

                            <div className="info">
                                {item.isZY && <span className="zy">自营</span>}
                            </div>
                        </div>
                    })}
                </div>
                <div style={{clear:'both'}}></div>
                <div className="page">
                    <div className="left page-btn" onClick={this.prevPage} 
                        style={{visibility: this.state.page === 1 ? 'hidden': 'visible'}}>上一页</div>
                    <div className="right page-btn" onClick={this.nextPage}>下一页</div>
                </div>
            </div>
        )
    }

    //发送AJAX 请求
    async componentDidMount() {
        //发送请求  axios({})  axios('')
        let result = await axios.get('http://127.0.0.1:8090/goods?_start=0&_limit=20');

        this.setState({
            goods: result.data
        })
    }

    nextPage = async () => { 
        // 页码数   1   2  3  4      n
        //         0  20 40  60    (n-1)*20
        let page = this.state.page;
        //页码自增
        page++;
        //计算 start
        let start = (page-1) * 20;
        //发送 AJAX 请求
        let result = await axios.get('http://127.0.0.1:8090/goods?_start='+start+'&_limit=20');
        //获取结果
        this.setState({
            goods: result.data,
            page: page
        });
        //将窗口滚动到指定位置
        window.scrollTo(0, 0);
    }

    prevPage = async () => {
        let page = this.state.page;
        //页码自增
        page--;
        //计算 start
        let start = (page-1) * 20;
        //发送 AJAX 请求    params 
        let result = await axios.get('http://127.0.0.1:8090/goods?_start='+start+'&_limit=20');
        //获取结果
        this.setState({
            goods: result.data,
            page: page
        });
        window.scrollTo(0, 0);
    }
}
